using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using cg;
using Proto;
using ProtoBuf.Meta;
using UnityEngine;

public class CreateByCode : MonoBehaviour
{
    private TypeModel mTypeModel;
    
    void Start()
    {
        Debug.Log($"[{GetType().FullName}] 这个脚本是通过代码AddComponent直接创建的");
        
        #if UNITY_EDITOR    
            mTypeModel = ProtoBuf.Meta.RuntimeTypeModel.Default;
        #else
            //打包的时候通过反射的方式来兼容热更新得到的 "protobuf-model"下的 "ProjectModel" 类
            var type = FindType("protobuf-model", "ProjectModel");
            var ctor = type.GetConstructor(Type.EmptyTypes);
            mTypeModel = (ProtoBuf.Meta.TypeModel) ctor.Invoke(null);
        #endif
            
            
            var msg = new C2G_Login();
            
            Debug.Log($"[{msg.GetType().FullName}] msgId = {MsgIdMap.GetMsgId(msg)}");

            var msgSize      = 524292;//512 * 1024 + 4;
            var packetStream = new MemoryStream(new byte[msgSize]);
            mTypeModel.Serialize(packetStream, msg);
            
            Debug.Log("看到一下消息说明数据序列化成功");
    }
    
    
    
    public static Assembly FindAssembly(in string assemblyName)
    {
        Assembly foundAsm   = null;
        var      assemblies = AppDomain.CurrentDomain.GetAssemblies();
        foreach( var asm in assemblies )
        {
            if( assemblyName == asm.GetName().Name )
            {
                foundAsm = asm;
                break;
            }
        }
            
        Debug.Log($"[AssemblyUtils] FindAssembly: {assemblyName} ({foundAsm})");
            
        return foundAsm;
    }

    public static Type FindType(in string assemblyName, in string typeName)
    {
        var asm  = FindAssembly(assemblyName);
        var type = asm?.GetType(typeName);
            
        Debug.Log($"[AssemblyUtils] FindType: {typeName} ({type})");
            
        return type;
    }
}
